package cn.jiaqiang.chatgpt.data.trigger.job;

import cn.jiaqiang.chatgpt.data.domain.order.service.IOrderService;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.CloseOrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description 超时关单任务
 */
@Slf4j
@Component()
public class TimeoutCloseOrderJob {

    @Autowired(required = false)
    private NativePayService payService;

    @Resource
    private IOrderService orderService;

    @Value("${wxpay.config.mchid}")
    private String mchid;

    /**
     * 每 10 分钟执行一次
     * 超时关单任务
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void exec() {
        try {
//            if (null == payService) {
//                log.info("定时任务，超时15分钟订单关闭。应用未配置支付渠道，任务不执行。");
//                return;
//            }
            // 查询超时15分钟，未支付订单
            List<String> orderIds = orderService.queryTimeoutCloseOrderList();
            if (orderIds == null || orderIds.isEmpty()) {
//                log.info("定时任务，超时15分钟订单关闭，暂无超时未支付订单 orderIds is empty");
                return;
            }
            for (String orderId : orderIds) {
                // 变更；订单支付关闭
                boolean status = orderService.changeOrderClose(orderId);
//                // 微信关单; 暂时不需要主动关闭
//                CloseOrderRequest request = new CloseOrderRequest();
//                request.setMchid(mchid);
//                request.setOutTradeNo(orderId);
//                payService.closeOrder(request);

                log.info("定时任务，超时15分钟订单关闭 orderId: {} status: {}", orderId, status);
            }
        } catch (Exception e) {
            log.error("定时任务，超时15分钟订单关闭失败", e);
        }
    }

}
